<template>
  <div class="flex">
    <el-select filterable v-model="size">
      <el-option
        v-for="item in billSizeOption"
        :label="item.label"
        :value="item.value"
      ></el-option>
    </el-select>
    <div class="ml-[16px]" v-if="size === 'custom'">
      <NumberRange
        :value="customSize"
        @input="customSize = $event"
        separate="*"
        :check-value="false"
        suffix="cm"
        :max="99999999999999"
      />
    </div>
  </div>
</template>
<script setup>
import NumberRange from '@/components/NumberRange/index.vue'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
  value: { type: Object, default: () => ({}) },
})

const emit = defineEmits(['input'])

const size = ref()
const customSize = ref({ min: undefined, max: undefined })

const billSizeOption = computed(() => {
  const { options } = props
  const _data = [
    {
      label: '自定义',
      value: 'custom',
    },
    ...options['bill_size'],
  ]
  return _data
})

watch(
  () => [size.value, customSize.value],
  val => {
    const [_size, _customSize] = val || []

    const _isCustom = _size === 'custom'
    const [l, w] = _size.split(',')

    const hasVal = _isCustom
      ? _customSize?.min !== undefined && _customSize?.max !== undefined
      : !!(l && w)
    emit(
      'input',
      hasVal
        ? {
            bill_size_l: _isCustom ? _customSize?.min + '' : l,
            bill_size_w: _isCustom ? _customSize?.max + '' : w,
          }
        : null
    )
  }
)

watch(
  () => props.value,
  (val, newVal) => {
    if (!val) return
    if (JSON.stringify(val) === JSON.stringify(newVal)) return
    const { bill_size_l, bill_size_w } = val || {}
    const map = billSizeOption.value?.map(n => n.value)
    const _item = map?.find(n => n === `${bill_size_l},${bill_size_w}`)
    if (_item) {
      customSize.value = {
        min: undefined,
        max: undefined,
      }
      size.value = _item
    } else {
      customSize.value = {
        min: bill_size_l,
        max: bill_size_w,
      }
      size.value = 'custom'
    }
  }
)
</script>
